import type { Role } from './role';
import { UserRole } from './user-role';

export class User {
  static readonly usernameMaxLength = 11;
  static readonly passwordMinLength = 6;
  static readonly passwordMaxLength = 20;
  static readonly fullNameMaxLength = 11;
  static readonly avatarUrlMaxLength = 200;
  static readonly descriptionMaxLength = 100;

  id?: string | null;
  username?: string | null;
  password?: string | null;
  fullName?: string | null;
  avatarUrl?: string | null;
  description?: string | null;
  isAccountGroupCreator?: boolean | null;
  enabled?: boolean | null;
  isAccountGroupAdmin?: boolean | null;
  fullRoles?: Role[] | null;

  static fromJSON(json: any): User {
    return {
      id: json.id,
      username: json.username,
      password: json.password,
      fullName: json.fullName,
      avatarUrl: json.avatarUrl,
      description: json.description,
      isAccountGroupCreator: json.isAccountGroupCreator,
      enabled: json.enabled,
      isAccountGroupAdmin: this.checkIsAccountGroupAdmin(json.fullRoles, json.isAccountGroupAdmin),
      fullRoles: json.fullRoles,
    };
  }

  /**
   * Checks if user is account group admin.
   */
  protected static checkIsAccountGroupAdmin(
    fullRoles: Role[],
    isAccountGroupAdmin: boolean | null,
  ): boolean {
    if (fullRoles?.length > 0) {
      return fullRoles.find((p) => p.authority!.indexOf(UserRole.accountGroupAdmin) > -1) != null;
    } else if (isAccountGroupAdmin != null) {
      return isAccountGroupAdmin;
    } else {
      return false;
    }
  }
}
